package com.dimeng;

import java.io.UnsupportedEncodingException;
import java.lang.ref.SoftReference;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;
import android.widget.Toast;

import com.dimeng.adapter.CompanySearchResultAdapter;
import com.dimeng.entity.ResultEntity;
import com.dimeng.entity.SearchResult;
import com.dimeng.utils.AppCache;
import com.dimeng.utils.CommonUtil;
import com.dimeng.utils.Constant;
import com.dimeng.utils.LoadDataThread;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * @author write by ccn<br>
 * <b>helloandroid100@gmail.com</b>
 * @version 0.1;2012-5-17 下午11:26:43<br>
 * descrition:公司搜索的视图类
 */
public class CompanySearchActivity extends SuperActivity {
	private static final long serialVersionUID = -5016034940339448007L;
	private Resources resources;
	private ListView listView;
	private ArrayAdapter<ResultEntity> arrayAdapter;
	private int firstVisiblePosition;
	private LinearLayout loadingLayout;
	private LinearLayout searchLayout;
	private TextView searchTypeNameTV;
	private ImageView indicateImageView;
	private boolean indicateFlag;
	private LinearLayout selectSearchLayout;
	/**弹出选择搜索类别的窗口**/
	private PopupWindow searchTypePopupWindow;
	/**弹出窗口popupWindow中的产品图像按钮**/
	private ImageButton prodImageButton;
	/**弹出窗口popupWindow中的求购图像按钮**/
	private ImageButton buyImageButton;
	/**弹出窗口popupWindow中的公司图像按钮**/
	private ImageButton comImageButton;
	private long total;//总记录数
	private int pageNum = 1;
	private long totalPage;//总页数
	/**弹出搜索结果的当前页、总页数视图**/
	private PopupWindow pageNumPopupWindow;
	
	private AutoCompleteTextView autoKeywordView;//自动提示输入搜索框
	private ArrayAdapter<String> autoAdapter;
	private Thread ajaxAutoCompleteThread;
	private List<String> autoKeywordList = new ArrayList<String>();
	private ImageButton searchButton;
	
	private TextView resultCountTextView;
	private TextView rightResultLabelTextView;
	
	private Button catNameButton;
	private Button regionButton;
	
	private final String COMPANY_SEARCH_URL = Constant.HOST_URL+"companySearch.do";//产品关键词搜索
	private String searchUrl;
	private String keyword = "";//搜索关键词
	private String lastKeyword = "";//上一次搜索的关键词
	private String clickItemKeyword="";//用户点击下拉的关键词
	private int regionId;//地区ID
	private String regionName;//地区名称
	private List<ResultEntity> searchResultList = new ArrayList<ResultEntity>();//搜索结果集列表
	private int pn = 1;//要加载数据的第几页的数据
	private LoadDataThread loadDataThread;
	private int msgWhat = -1;
	
	private Context context;
	
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			loadingLayout.setVisibility(View.GONE);
			msgWhat = msg.what;
			switch (msgWhat) {
				case 0:
					Toast.makeText(CompanySearchActivity.this, "已经加载完所有的数据了", Toast.LENGTH_SHORT).show();
					break;
				case 1:
					String json = (String) msg.obj;
					SearchResult searchResult = new Gson().fromJson(json, new TypeToken<SearchResult>(){}.getType());
					if(null != searchResult){
						total = searchResult.getTotal();
						totalPage = total%Constant.PAGE_SIZE == 0 ? total/Constant.PAGE_SIZE : total/Constant.PAGE_SIZE+1;
						resultCountTextView.setText(total+"");
						List<ResultEntity> resultEntities = searchResult.getResultList();
						if(null != resultEntities){
							++pn;
							searchResultList.addAll(resultEntities);
							arrayAdapter.notifyDataSetChanged();
							listView.setSelection(firstVisiblePosition-1);
						}
					}
					break;
				case 2:
					Toast.makeText(CompanySearchActivity.this, Constant.NET_ERROR, Toast.LENGTH_LONG).show();
					break;
				case 3://动态加载关键词
					if(!clickItemKeyword.equals(keyword)){
						autoAdapter = new ArrayAdapter<String>(CompanySearchActivity.this, R.layout.autotextview_item,autoKeywordList);
						autoKeywordView.setAdapter(autoAdapter);
						autoAdapter.notifyDataSetChanged();
					}
					break;
				default:
					break;
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search);
		context = this;
		resources = getResources();
		Intent intent = getIntent();
		String key = intent.getStringExtra("keyword");
		if(null != key && !"".equals(key.trim()))
			keyword = key.trim();
		//加载非当前视图文件“setContentView(R.layout.cat_search)”中定义的视图组件
		selectSearchLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.select_search_type, null);
		prodImageButton = (ImageButton) selectSearchLayout.getChildAt(0);//从弹出窗布局selectSearchLayout中获取第一个组件
		buyImageButton = (ImageButton) selectSearchLayout.getChildAt(1);//从弹出窗布局selectSearchLayout中获取第二个组件
		comImageButton = (ImageButton) selectSearchLayout.getChildAt(2);//从弹出窗布局selectSearchLayout中获取第三个组件
		CommonUtil.setButtonFocusChanged(prodImageButton);//设置图像按钮被点击的效果
		CommonUtil.setButtonFocusChanged(buyImageButton);//设置图像按钮被点击的效果
		CommonUtil.setButtonFocusChanged(comImageButton);
		
		resultCountTextView = (TextView) findViewById(R.id.resultCount);
		rightResultLabelTextView = (TextView) findViewById(R.id.rightResultLabelId);
		rightResultLabelTextView.setText(resources.getString(R.string.rightResultCompanyLabel));
		catNameButton = (Button) findViewById(R.id.catNameButton);
		regionButton = (Button) findViewById(R.id.regionButton);
		String rid = intent.getStringExtra("regionId");
		if(null != rid && !"".equals(rid)){
			try {
				regionId = Integer.parseInt(rid);
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
		}
		regionName = intent.getStringExtra("regionName");
		if(null != regionName && !"".equals(regionName))
			regionButton.setText(regionName);
		
		searchLayout = (LinearLayout) this.findViewById(R.id.searchLayoutId);
		listView = (ListView) findViewById(R.id.catSearchResultListView);
		searchTypeNameTV = (TextView) findViewById(R.id.searchTypeNameId);
		String companyType = resources.getString(R.string.company);
		searchTypeNameTV.setText(companyType);
		indicateImageView = (ImageView) findViewById(R.id.searchTypeIndicate);
		searchButton = (ImageButton) findViewById(R.id.searchButton);
		CommonUtil.setButtonFocusChanged(searchButton);
		autoKeywordView = (AutoCompleteTextView) findViewById(R.id.keywordId);
		
		autoKeywordView.setThreshold(1);//设置输入1个字符后提示
		if(!"".equals(keyword)){
			autoKeywordView.setText(keyword);
		}
		
		autoKeywordView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				pn = 1 ;
				firstVisiblePosition = 0;
				
				clickItemKeyword = autoAdapter.getItem(position).toLowerCase().trim();
				keyword = clickItemKeyword;
				searchResultList.clear();
				arrayAdapter.notifyDataSetChanged();
				search();
			}
		});
		autoKeywordView.addTextChangedListener(new TextWatcher(){
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				pn = 1 ;
				firstVisiblePosition = 0;
				regionId = 0;
				regionButton.setText(resources.getString(R.string.region));
				
				keyword = autoKeywordView.getText().toString().toLowerCase().trim();
				getAutoKeywords();
			}
			public void afterTextChanged(Editable s) {
				
			}
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
		});
		searchTypePopupWindow = new PopupWindow(selectSearchLayout);
		
		final TextView pageNumTextView = new TextView(this);
		pageNumPopupWindow = new PopupWindow(pageNumTextView);
		pageNumPopupWindow.setWidth(LayoutParams.WRAP_CONTENT);
		pageNumPopupWindow.setHeight(LayoutParams.WRAP_CONTENT);
		pageNumPopupWindow.setBackgroundDrawable(resources.getDrawable(R.drawable.catListBG));
		pageNumPopupWindow.setOutsideTouchable(true);
		pageNumPopupWindow.setFocusable(true);
		
		loadingLayout = CommonUtil.loadingLayout(this);
		arrayAdapter = new CompanySearchResultAdapter(CompanySearchActivity.this,searchResultList);
		listView.setAdapter(arrayAdapter);
		listView.addFooterView(loadingLayout);
		search();//开始发送搜索请求
		
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> adapter, View view, int location,
					long id) {
				ResultEntity prodSearchResult = searchResultList.get(location);
				Intent intent = new Intent(CompanySearchActivity.this,WebViewActivity.class);
				intent.putExtra("url", prodSearchResult.getDetailUrl());
				CompanySearchActivity.this.startActivity(intent);
			}
		});
		
		listView.setOnScrollListener(new OnScrollListener() {
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if(OnScrollListener.SCROLL_STATE_IDLE == scrollState){
					pageNumPopupWindow.setFocusable(false);
					pageNumPopupWindow.dismiss();
				}
				
				if(OnScrollListener.SCROLL_STATE_TOUCH_SCROLL == scrollState){
					pageNumPopupWindow.showAtLocation(listView, Gravity.RIGHT, 10, 0);//设置页码提示视图所在的位置
					pageNumPopupWindow.update();
				}
			}
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if(msgWhat == 1 && (firstVisibleItem + visibleItemCount == totalItemCount) && totalItemCount > Constant.PAGE_SIZE){
					firstVisiblePosition = totalItemCount;
					search();
				}
				if((msgWhat == 0 || msgWhat == 1)){
					int a = (firstVisibleItem+1)%Constant.PAGE_SIZE;
					int b = (firstVisibleItem+1)/Constant.PAGE_SIZE;
					pageNum = a == 0 ?b:b+1;
					if(pageNum > totalPage)
						pageNum = (int) totalPage;
					pageNumTextView.setText(pageNum+"/"+totalPage+"页");
				}
			}
		});
		
		searchLayout.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(!indicateFlag){
					indicateFlag = true;
					indicateImageView.setImageDrawable(resources.getDrawable(R.drawable.up));
					
					searchTypePopupWindow.setWidth(searchLayout.getWidth()-searchButton.getWidth()-4);
					searchTypePopupWindow.setHeight(LayoutParams.WRAP_CONTENT);
					searchTypePopupWindow.setBackgroundDrawable(resources.getDrawable(R.drawable.catListBG));
					searchTypePopupWindow.showAsDropDown(searchTypeNameTV, 0, 0);
					searchTypePopupWindow.setOutsideTouchable(true);
					searchTypePopupWindow.setFocusable(true);
					searchTypePopupWindow.update();
				} else {
					indicateFlag = false;
					indicateImageView.setImageDrawable(resources.getDrawable(R.drawable.down));
					if(null != searchTypePopupWindow) {
						searchTypePopupWindow.setFocusable(false);
						searchTypePopupWindow.dismiss();
					}
				}
			}
		});
		
		searchTypePopupWindow.setOnDismissListener(new OnDismissListener() {
			public void onDismiss() {
				indicateFlag = false;
				indicateImageView.setImageDrawable(resources.getDrawable(R.drawable.down));
			}
		});
		
		prodImageButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(CompanySearchActivity.this,SupplyBuySearchActivity.class);
				intent.putExtra("keyword", keyword);
				intent.putExtra("searchType", 1);
				CompanySearchActivity.this.startActivity(intent);
			}
		});
		buyImageButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(CompanySearchActivity.this,SupplyBuySearchActivity.class);
				intent.putExtra("keyword", keyword);
				intent.putExtra("searchType", 3);
				CompanySearchActivity.this.startActivity(intent);
			}
		});
		comImageButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				searchTypePopupWindow.setFocusable(false);
				searchTypePopupWindow.dismiss();
			}
		});
		
		searchButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if("".equals(keyword)){//使用动画提醒用户
					Animation shake = AnimationUtils.loadAnimation(context, R.anim.animlayout);
					searchLayout.startAnimation(shake);
					return;
				}
				if(!lastKeyword.equals(keyword)){
					searchResultList.clear();
					arrayAdapter.notifyDataSetChanged();
					pn = 1;
					firstVisiblePosition = 0;
					search();
				}
			}
		});
		
		catNameButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(CompanySearchActivity.this,CatBrowseActivity.class);//转到类别浏览视图,从顶级类目开始浏览
				CompanySearchActivity.this.startActivity(intent);
			}
		});
		
		regionButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(CompanySearchActivity.this,FilterRegionActivity.class);//转到类别浏览视图,从顶级类目开始浏览
				intent.putExtra("keyword", keyword);
				intent.putExtra("searchType", 2);
				intent.putExtra("regionName", regionName);
				intent.putExtra("class", CompanySearchActivity.class);
				CompanySearchActivity.this.startActivity(intent);
			}
		});
	}
	
	/**获取自动提示的关键词**/
	private void getAutoKeywords(){
		if(!"".equals(keyword) && !clickItemKeyword.equals(keyword)) {
			clickItemKeyword = "";
			final Message msg = new Message();
			SoftReference<List<String>> sr = AppCache.autoCompleteKeywordMap.get(keyword);
			if(null != sr){//从缓存中取出自动提示的关键词
				List<String> data = sr.get();
				if(null != data){
					autoKeywordList = new ArrayList<String>();
					autoKeywordList.clear();
					autoKeywordList.addAll(data);
					msg.what = 3;
					handler.sendMessage(msg);
				}
			} else {//从服务器中下载自动提示的关键词
				String categoryName = "";
				try {
					categoryName = URLEncoder.encode(keyword,Constant.CHARSET_GBK);
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				}
				final String url = Constant.HOST_URL + "autocomplteKeywordName.do?categoryName="+categoryName;
				if(null == ajaxAutoCompleteThread || !ajaxAutoCompleteThread.isAlive()){
					ajaxAutoCompleteThread = new Thread(){
						@Override
						public void run() {
							try {
								String json = CommonUtil.getContent(url, Constant.CHARSET_GBK,true);
								List<String> autoKeywords = new Gson().fromJson(json, new TypeToken<List<String>>(){}.getType());
								if(null != autoKeywords && autoKeywords.size() >0){
									autoKeywordList = new ArrayList<String>();
									autoKeywordList.clear();
									autoKeywordList.addAll(autoKeywords);
									msg.what = 3;
									handler.sendMessage(msg);
									
									SoftReference<List<String>> sr = new SoftReference<List<String>>(autoKeywords);
									AppCache.autoCompleteKeywordMap.put(keyword,sr);//把autoKeywords加入缓存
								}
							} catch (Exception e) {
								msg.what = 4;
								handler.sendMessage(msg);
								e.printStackTrace();
							}
						}
					};
					ajaxAutoCompleteThread.start();
				}
			}
		}
	}
	
	/**
	 * 发送搜索请求
	 * @param prefixSearchUrl 搜索的action
	 */
	private void search(){
		if(!"".equals(keyword)){
			try {
				lastKeyword = keyword;
				String encodeKeyword = URLEncoder.encode(keyword,Constant.CHARSET_GBK);//对关键词进行GBK编码后作为请求参数
				searchUrl = COMPANY_SEARCH_URL +"?q="+encodeKeyword+"&regionId="+regionId+"&pn="+pn;
				startLoadDataThread(searchUrl);//开始发送搜索请求
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**启动线程下载数据**/
	private void startLoadDataThread(String url){
		if(null == loadDataThread || !loadDataThread.isAlive()){
			loadDataThread = new LoadDataThread(url,Constant.CHARSET_GBK,handler,false);
			loadDataThread.start();
			loadingLayout.setVisibility(View.VISIBLE);
		}
	}
	
}
